package config

import (
	"fmt"
	"gitee.com/getcharzp/light-ftp/define"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/up-zero/gotool/streamutil"
	"os"
)

func Create(cfg *define.SiteConfig) {
	if _, err := tea.NewProgram(initialModel(cfg, nil)).Run(); err != nil {
		fmt.Printf("could not start program: %s\n", err)
		os.Exit(1)
	}
}

func createImpl(cfg *define.SiteConfig) error {
	sysCfg := new(define.SysConfig)
	if err := sysCfg.Read(); err != nil {
		return err
	}
	for _, site := range sysCfg.Sites {
		if site.Name == cfg.Name {
			return fmt.Errorf("站点名称已存在")
		}
	}
	sysCfg.Sites = append(sysCfg.Sites, *cfg)
	return sysCfg.Save()
}

func List() {
	sysConfig := &define.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	showList(sysConfig.Sites)
}

func Delete(name string) {
	sysConfig := &define.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}

	sites := streamutil.NewStream(sysConfig.Sites).Filter(func(item define.SiteConfig) bool {
		return item.Name != name
	}).ToSlice()
	if len(sites) == len(sysConfig.Sites) {
		fmt.Println("站点不存在")
		os.Exit(1)
	}

	sysConfig.Sites = sites
	if err := sysConfig.Save(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	fmt.Println("删除成功")
}

func Edit(name string) {
	// 1. 系统配置
	sysConfig := &define.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	// 2. 获取站点idx
	var index *int
	for i, site := range sysConfig.Sites {
		if site.Name == name {
			index = &i
			break
		}
	}
	if index == nil {
		fmt.Println("light ftp config error. site not found.")
		os.Exit(1)
	}
	if _, err := tea.NewProgram(initialModel(&sysConfig.Sites[*index], index)).Run(); err != nil {
		fmt.Printf("could not start program: %s\n", err)
		os.Exit(1)
	}
}

func editImpl(cfg *define.SiteConfig, index *int) error {
	sysConfig := &define.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	sysConfig.Sites[*index] = *cfg
	return sysConfig.Save()
}
